package com.qf.first.base.handler;

import com.qf.first.base.exception.BaseException;
import com.qf.first.base.result.RespVo;
import com.qf.first.base.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public RespVo handlerException(RuntimeException ex){
        log.error(ex.getMessage());
        return RespVo.error();
    }

    @ExceptionHandler(BaseException.class)
    public RespVo handlerException(BaseException ex){
        log.error(ex.getMessage());
        return RespVo.error();
    }

    /**
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RespVo<Object> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String msg = allErrors.get(0).getDefaultMessage();
        log.error(msg);
        return RespVo.error(ResultCode.ERROR.getCode(),msg);
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public RespVo<Object> ConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        String msg = constraintViolations.iterator().next().getMessageTemplate();
        log.error(msg);
        return RespVo.error(ResultCode.ERROR.getCode(),msg);
    }
}
